package com.mysteel.monitor.servlet;

import com.alibaba.fastjson.JSON;
import com.mysteel.monitor.core.Handler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.HashSet;
import java.util.Set;

/**
 *  主要的monitor
 */
public class MysteelMonitorServlet extends ResourceServlet {
    private static  final Logger logger = LoggerFactory.getLogger(MysteelMonitorServlet.class);
    private String      mappingPath = "views";
    private Set<String> mapping     = new HashSet<String>();

    public MysteelMonitorServlet(){
        //页面
        super("views/html");
        mapping.add("/css/monitor.css");
        // echart 图表
        mapping.add("/js/echarts.min.js");
        mapping.add("/js/jquery-3.4.0.min.js");
        mapping.add("/js/monitor.js");
        //layui
        mapping.add("/layui/css/layui.css");
        mapping.add("/layui/layui.all.js");
    }

    public MysteelMonitorServlet(String resourcePath) {
        super(resourcePath);
    }

    @Override
    protected String getFilePath(String fileName) {
        if (mapping.contains(fileName) || fileName.startsWith("/layui")) {
            return mappingPath + fileName;
        }

        return super.getFilePath(fileName);
    }

    @Override
    protected String process(String url, HttpServletRequest request, HttpServletResponse response) throws IOException {

        Handler handler = urlMaps.get(url.replaceAll(".json",""));
        if(handler == null ){
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return "";
        }
        else{
            Class cls = handler.getActionClass();
            Method method = handler.getActionMethod();
            try {
                Type[] parameterTypes = method.getGenericParameterTypes();
                Object result = null;
                if(parameterTypes == null || parameterTypes.length  == 0) {
                    result= method.invoke(cls.newInstance(), new Object[]{});
                }else{
                    // 判断是否参入httpservlet第一个参数
                    if(HttpServletRequest.class.getTypeName().equals(parameterTypes[0].getTypeName())){
                        result= method.invoke(cls.newInstance(), request);
                    }
                }
                return JSON.toJSONString(result);
            } catch (Exception  e) {
                logger.error("【{}】",url,e);
            }

        }
        return null;
    }

}
